// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Z [author] rhyme_lph
// L [email]  rhymelph@gmail.com
// D [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/sub_cards_entity.dart';
import 'package:finance_app/src/http_service/http_subscription_service.dart';
import 'package:finance_app/src/provider/setting/subscription/sub_payment_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';

class SubPaymentMethodManagerProvider
    extends BaseProvider<List<SubCardsEntity>> {
  SubCardsEntity select;

  @override
  Future get dataFuture => HttpSubscriptionService.getSubscriptionsCards();

  void onAddCreditCard() async {
    String paymentUrl;
    int subscriptionId;
    await post(HttpSubscriptionService.cardsNew(),
        loadingTip: S.current.loading,
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      paymentUrl = result.data['data']['payment_url'];
      subscriptionId = result.data['data']['subscription_id'];
    });
    if (paymentUrl != null) {
      final result =
          await Routes.navigateTo(RouterGenProviders.webViewPage, params: {
        'url': paymentUrl,
        'isAdd': true,
      });
      if (result is Map && result['isSeeInvoice'] == true) {
        //跳转到 See Invoice
        onTry();
        final payment = Providers.get<SubPaymentProvider>(
            RouterGenProviders.subPaymentPage, null);
        payment?.loadCards();
        obtainContext?.call((context) {
          Routes.navigateTo(RouterGenProviders.subInvoicePage, params: {
            'id': subscriptionId,
          });
        });
      } else if (result is Map && result['isSuccess'] == true) {
        onTry();
        final payment = Providers.get<SubPaymentProvider>(
            RouterGenProviders.subPaymentPage, null);
        payment?.loadCards();
      }
    }
    // Routes.navigateTo(RouterGenProviders.subAddCreditCardPage);
  }

  void onDelete(SubCardsEntity value) {
    obtainContext?.call((context) async {
      if (value.isDefault == 1) {
        await showPayAnotherCardBeforeRemovingTipBottomSheet(context);
        return;
      }
      final result =
          await showRemovePaymentMethodBottomSheet(context, value.cardNumber);
      if (result == true) {
        bool isSuccess = false;
        await post(HttpSubscriptionService.deleteCards(value.tokenId),
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isSuccess = true;
        }, loadingTip: S.current.loading);
        if (isSuccess == true) {
          await showPaymentMethodRemoveSuccessBottomSheet(context);
          onTry();
          final payment = Providers.get<SubPaymentProvider>(
              RouterGenProviders.subPaymentPage, null);
          payment?.loadCards(true);
        }
      }
    });
  }

  void onSelect(SubCardsEntity value) {
    if (value.tokenId != select.tokenId) {
      obtainContext?.call((context) async {
        final result =
            await showChangePaymentMethodBottomSheet(context, value.cardNumber);
        if (result == true) {
          bool isSuccess = false;

          await post(HttpSubscriptionService.setDefaultCard(value.tokenId),
              autoHandler: AutoHandler.Toast,
              loadingTip: S.current.loading, onSuccess: (value) {
            isSuccess = true;
          });
          if (isSuccess) {
            select = value;
            update();
            final payment = Providers.get<SubPaymentProvider>(
                RouterGenProviders.subPaymentPage, null);
            payment?.loadCards(true);
          }
        }
      });
    }
  }

  @override
  FutureOr<List<SubCardsEntity>> transformData(
      List<SubCardsEntity> d, bool isCache) {
    if (d.length > 0) {
      select =
          d.firstWhere((element) => element.isDefault == 1, orElse: () => null);
    }
    return super.transformData(d, isCache);
  }
}
